package me

type Page struct {
	last [2]int
	// 总长度、每页长度、总页数、当前页数
	totalLen, perPage, totalPage, curPage int
}

func NewPage(totalLen, perPage int) *Page {
	if totalLen == 0 {
		return nil
	}
	bp := &Page{totalLen: totalLen}
	bp.SetPageSize(perPage)
	return bp
}

func (bp *Page) SetPageSize(perPage int) *Page {
	if perPage > bp.totalLen {
		perPage = bp.totalLen
		bp.totalLen = perPage
	}
	if perPage < 1 {
		perPage = bp.totalLen / 2
	}
	bp.perPage = perPage
	bp.curPage = 1
	// 总页数
	shang := bp.totalLen / perPage
	// 余数
	yushu := bp.totalLen % perPage
	if yushu > 0 {
		bp.totalPage = shang + 1
		bp.last = [2]int{shang * perPage, bp.totalLen}
	} else {
		bp.totalPage = shang
		bp.last = [2]int{(shang - 1) * perPage, bp.totalLen}
	}

	return bp
}
func (bp *Page) TotalPage() int {
	return bp.totalPage
}
func (bp *Page) CurPage() int {
	return bp.curPage
}
func (bp *Page) CurIndexs() (int, int) {
	if bp.curPage < bp.totalPage {
		return (bp.curPage - 1) * bp.perPage, bp.curPage * bp.perPage
	} else {
		return bp.Last()
	}
}
func (bp *Page) GetPage(page int) (int, int) {
	bp.curPage = page
	return bp.CurIndexs()
}
func (bp *Page) First() (int, int) {
	bp.curPage = 1
	return bp.CurIndexs()
}
func (bp *Page) Last() (int, int) {
	bp.curPage = bp.totalPage
	return bp.last[0], bp.last[1]
}
func (bp *Page) Next() (int, int) {
	bp.curPage++
	return bp.CurIndexs()
}
func (bp *Page) Prev() (int, int) {
	if bp.curPage > 1 {
		bp.curPage--
	}
	return bp.CurIndexs()
}
